package com.ultrasoft.farmasoft.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.ultrasoft.farmasoft.domain.Accountreceivable;
import com.ultrasoft.farmasoft.domain.Activesubstance;
import com.ultrasoft.farmasoft.domain.Attribute;
import com.ultrasoft.farmasoft.domain.Client;
import com.ultrasoft.farmasoft.domain.Composition;
import com.ultrasoft.farmasoft.domain.Item;
import com.ultrasoft.farmasoft.domain.Package;
import com.ultrasoft.farmasoft.domain.Paymentplan;
import com.ultrasoft.farmasoft.domain.Pharmacyproduct;
import com.ultrasoft.farmasoft.domain.Product;
import com.ultrasoft.farmasoft.domain.Productattribute;
import com.ultrasoft.farmasoft.domain.Productattributes;
import com.ultrasoft.farmasoft.domain.Provider;
import com.ultrasoft.farmasoft.domain.Stock;
import com.ultrasoft.farmasoft.domain.Typecomposition;
import com.ultrasoft.farmasoft.domain.Userpharmacy;
import com.ultrasoft.farmasoft.exceptions.ExceptionObject;
import com.ultrasoft.farmasoft.repository.ClientDao;
import com.ultrasoft.farmasoft.service.BuyProductsTransactionService;
import com.ultrasoft.farmasoft.service.ConfigServiceProducts;
import com.ultrasoft.farmasoft.service.StockService;
import com.ultrasoft.farmasoft.util.UtilCommon;
import com.ultrasoft.farmasoft.util.UtilConverter;
import com.ultrasoft.farmasoft.util.UtilTransaction;




@Controller
@SessionAttributes({"s_UserPharmacy"}) 
@RequestMapping(value="/Transaction")
public class TransactionSellProductsController {
	private HttpSession session;
	private Userpharmacy s_UserPharmacy;
	private int s_userId;
	private int s_pharmacyId;
	
	private List<Product> listProductGlobal;
	
	private final ConfigServiceProducts configServiceProducts;
	private final StockService stockService;
	private final BuyProductsTransactionService buyProductsTransactionService;
	
	@Autowired
	public TransactionSellProductsController(BuyProductsTransactionService buyProductsTransactionService,ConfigServiceProducts configServiceProducts,StockService stockService){
		this.configServiceProducts 				= configServiceProducts;
		this.stockService 						= stockService;
		this.buyProductsTransactionService		= buyProductsTransactionService;
	}
	
	private boolean sessionControl(HttpServletRequest request){
		boolean res = false;
		session = request.getSession(true);
		if(session.getAttribute("s_UserPharmacy") != null){
			s_UserPharmacy 	= (Userpharmacy)session.getAttribute("s_UserPharmacy");
			s_userId 		= s_UserPharmacy.getUser().getUserId();
			s_pharmacyId 	= s_UserPharmacy.getPharmacy().getPharmacyId();
			res = true;
		}
		return res;
	}
	private String redirectTransactionSellProducts(HttpServletRequest request){
		if(!sessionControl(request))
			return "redirect:/index"; 
		else
			return "redirect:/sellProducts?"+UtilCommon.menuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.menuId_)+"&"+UtilCommon.subMenuId_+"="+UtilConverter.converterStringToShort(request,UtilCommon.subMenuId_); 
	}
	@RequestMapping(value="/sellProducts", method=RequestMethod.GET)
	public String handleRequestTransactionSellProducts(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){				
			this.listProductGlobal 	= new ArrayList<Product>();			
			List<Product> listProduct = configServiceProducts.getListProductByPharmacyId(s_pharmacyId,true);
			List<Product> listProductTemp	= new ArrayList<Product>();
			for (Product product : listProduct) {
				listProductTemp.add(getProductTempOnlyProductAttributesOnlyTypeCompositionOnlyActiveSubstance(product));
			}			
			model.addAttribute("listProductDetail",listProductTemp);
			model.addAttribute("listPharmacyStock",stockService.getListPharmacyStockByPharmacyId(s_pharmacyId));
			configServiceProducts.setFreeItemsFreePackageToProductByPharmacyIdByTempStateByActive(s_pharmacyId,(short)s_userId,true);
			return UtilCommon.fTransaction_SellProducts+"saleProducts";
		}else
			return redirectTransactionSellProducts(request);
	}
	
	@RequestMapping(value = "/saleLoadTableTempByStock", method = RequestMethod.GET)
   	public @ResponseBody List<Product> handleRequestSaleLoadTableTempByStock(HttpServletRequest request){	// (short)1 	: active 
		System.out.println(getListProductTempWithItems(configServiceProducts.getListProductByPharmacyIdByActiveByStockId(s_pharmacyId,true,UtilConverter.converterStringToInteger(request,"stockId"))));
		return productSelectedAdd(getListProductTempWithItems(configServiceProducts.getListProductByPharmacyIdByActiveByStockId(s_pharmacyId,true,UtilConverter.converterStringToInteger(request,"stockId"))));
	}
	
	@RequestMapping(value = "/saleSellItemsProduct", method = RequestMethod.GET)
   	public @ResponseBody Map<String, Object> handleRequestSaleSellItemsProduct(HttpServletRequest request){	// (short)1 	: UtilConverter.converterStringToInteger(request,"_providerId"),UtilConverter.converterStringToInteger(request,"_productId") 
		Map<String, Object> map = new HashMap<String,Object>();
		short stateItemOld = UtilConverter.converterStringToShort(request,"stateItemOld");
		short stateItemNew = UtilConverter.converterStringToShort(request,"stateItemNew");
		short sUserId = UtilConverter.converterStringToShort(request,"sUserId");		
		
		int contUnits = UtilConverter.converterStringToInteger(request,"_units");
		Product pSearch = getProductTemp(configServiceProducts.searchProductByProviderIdByProductId(UtilConverter.converterStringToInteger(request,"_providerId"),UtilConverter.converterStringToInteger(request,"_productId"), s_pharmacyId, true, UtilConverter.converterStringToInteger(request,"stockId")));
		int cOne 	= 0;		
		int cThree 	= 0;		
		
		Product  p= null;		
		if(listProductGlobal.isEmpty()){
			p = pSearch;
			listProductGlobal.add(p);
		}else{
			for (Product pTemp : listProductGlobal) {
				if(pTemp.getProductPK().getProviderId() == pSearch.getProductPK().getProviderId() && pTemp.getProductPK().getProductId() == pSearch.getProductPK().getProductId())
					p = pTemp;
			}
			if(p == null){
				p = pSearch;
				listProductGlobal.add(p);
			}			
		}		
		List<Item> listItemTempUpdate 	=  new ArrayList<Item>();		
		List<Package> listPackTempUpdate=  new ArrayList<Package>();
		
		List<Item> listItemTemp =  new ArrayList<Item>();		
		for (Package package1 : p.getPharmacyProduct().getPackageCollection()) {
			for (Item item : package1.getItemCollection()) {
				if(item.getState() == stateItemOld){
					if(cOne < contUnits && stateItemOld == (short)1){
						item.setState(stateItemNew);
						Item itemTemp = new Item(item.getItemPK().getPackageId(),item.getItemPK().getItemId());
						itemTemp.setCost(item.getCost());
						itemTemp.setState(item.getState());
						itemTemp.setStockId(item.getStockId());

						if(stateItemOld == (short)1)
							item.setTempState(sUserId);
						if(stateItemOld == (short)3)
							item.setTempState((short)0);
						
						itemTemp.setTempState(item.getTempState());
						listItemTemp.add(itemTemp);
						listItemTempUpdate.add(item);
						cOne++;
					}else
						if(cThree < contUnits && stateItemOld == (short)3 && item.getTempState() == (short)sUserId ){
							item.setState(stateItemNew);
							Item itemTemp = new Item(item.getItemPK().getPackageId(),item.getItemPK().getItemId());
							itemTemp.setCost(item.getCost());
							itemTemp.setState(item.getState());
							itemTemp.setStockId(item.getStockId());
	
							if(stateItemOld == (short)1)
								item.setTempState(sUserId);
							if(stateItemOld == (short)3)
								item.setTempState((short)0);
							
							itemTemp.setTempState(item.getTempState());
							listItemTemp.add(itemTemp);
							listItemTempUpdate.add(item);
							cThree++;
						}
				}	
			}
			
			int one 	= 0;
			int three 	= 0;
			for (Item itemElement : package1.getItemCollection()) {
				if(itemElement.getState() == (short)1)
					one++;
				if(itemElement.getState() == (short)3)
					three++;
					
			}
			if(one > 0){
				package1.setState((short)1);
				listPackTempUpdate.add(package1);
			}
			else
				if(three > 0){
					package1.setState((short)3);
					listPackTempUpdate.add(package1);
				}
		}		
		if(!listItemTempUpdate.isEmpty())
			buyProductsTransactionService.updateItemByListItem(listItemTempUpdate);
		if(!listPackTempUpdate.isEmpty())
			buyProductsTransactionService.updatePackageByListPackage(listPackTempUpdate);				
		
		map.put("p",p);
		map.put("list",productSelectedAdd(getListProductTempWithItems(configServiceProducts.getListProductByPharmacyIdByActiveByStockId(s_pharmacyId,true,UtilConverter.converterStringToInteger(request,"stockId")))));
		map.put("listItem",listItemTemp);			
		// map.put("accountReceivable", arg1)
		
		Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String parameterName = (String) enumeration.nextElement();
            System.out.print(parameterName+"   < ***** >");
            System.out.println(request.getParameter(parameterName));
        }		
		return map;
    }
	
	private List<Product> productSelectedAdd(List<Product> list){
		for (Product product : list) {
			if(product.getPharmacyProduct() != null){
				Pharmacyproduct  pp= product.getPharmacyProduct();
				for (Package package1 : pp.getPackageCollection()) {
					for (Product product2 : listProductGlobal) {
						if(product2.getPharmacyProduct() != null){
							Pharmacyproduct pp2 = product2.getPharmacyProduct();
							for (Package package2 : pp2.getPackageCollection()) {
								if(package2.getPackage1() == package1.getPackage1()){
									package1.setState(package2.getState());
									for (Item item1 : package1.getItemCollection()) {
										for (Item item2 : package2.getItemCollection()) {
											if(item1.getItemPK().getItemId() == item2.getItemPK().getItemId() && item1.getItemPK().getPackageId() == item2.getItemPK().getPackageId()){
												item1.setState(item2.getState());
											}
										}
									}									
								}
							}
						}
					}					
				}
			}
		}
		return list;
	}
	
	@RequestMapping(value = "/saleLoadTableTempByName", method = RequestMethod.GET)
   	public @ResponseBody List<Product> handleRequestSaleLoadTableTempByName(HttpServletRequest request){		
		return productSelectedAdd(getListProductTempWithItems(configServiceProducts.getListProductByPharmacyIdByActiveByStockIdByName(s_pharmacyId,true,UtilConverter.converterStringToInteger(request,"stockId"),UtilConverter.converterStringToString(request,"name"))));
    }
	
	@RequestMapping(value = "/saleLoadTableTempByCode", method = RequestMethod.GET)
   	public @ResponseBody List<Product> handleRequestSaleLoadTableTempByCode(HttpServletRequest request){		
		return productSelectedAdd(getListProductTempWithItems(configServiceProducts.getListProductByPharmacyIdByActiveByStockIdByCode(s_pharmacyId,true,UtilConverter.converterStringToInteger(request,"stockId"),UtilConverter.converterStringToString(request,"code"))));
    }
	
	@RequestMapping(value = "/saleLoadTableTempByCodeBar", method = RequestMethod.GET)
   	public @ResponseBody List<Product> handleRequestSaleLoadTableTempByCodeBar(HttpServletRequest request){		
		return productSelectedAdd(getListProductTempWithItems(configServiceProducts.getListProductByPharmacyIdByActiveByStockIdByCodeBar(s_pharmacyId,true,UtilConverter.converterStringToInteger(request,"stockId"),UtilConverter.converterStringToString(request,"codeBar"))));
    }
	
	private Product getProductTempOnlyProductAttributesOnlyTypeCompositionOnlyActiveSubstance(Product product){
		Product p = new Product(product.getProductPK().getProviderId(),product.getProductPK().getProductId());
		p.setName(product.getName());
		p.setPresentation(product.getPresentation());
		p.setActive(product.getActive());
		p.setGenericName(product.getGenericName());
		p.setCode(product.getCode());
		p.setCodeBar(product.getCodeBar());
		p.setGeneralIndication(product.getGeneralIndication());
		if(product.getActiveSubstanceId() != null){
			Activesubstance as = new Activesubstance(product.getActiveSubstanceId().getActiveSubstanceId(),product.getActiveSubstanceId().getSynonyms(),product.getActiveSubstanceId().getName(),product.getActiveSubstanceId().getTherapeuticAction(),product.getActiveSubstanceId().getProperties());
			if(as != null){
				List<Attribute> listAttributeTemp = (List<Attribute>)product.getActiveSubstanceId().getAttributeCollection();
				List<Attribute> listAttribute = new ArrayList<Attribute>();
				for (Attribute a : listAttributeTemp) {
					Attribute attribute = new Attribute(a.getAttributePK().getAttributeId(),a.getAttributePK().getActiveSubstanceId(), a.getName(), a.getDetail(), a.getOrder());
					listAttribute.add(attribute);
				}
				as.setAttributeCollection(listAttribute);
			}
			p.setActiveSubstanceId(as);
		}
		List<Composition> listCompositionTemp = (List<Composition>)product.getCompositionCollection();
		List<Composition> listComposition = new ArrayList<Composition>();
		for (Composition c : listCompositionTemp) {
			Composition composition = new Composition(c.getCompositionId(),c.getName(),c.getQuantity(),c.getActive());
			composition.setValueRadio(c.getValueRadio());
			composition.setQuantity(c.getQuantity());
			composition.setCheckHealth(c.getCheckHealth());
			composition.setDetailCheckHealth(c.getDetailCheckHealth());
			Typecomposition typeComposition = new Typecomposition(c.getTypeCompositionId().getTypeCompositionId(),c.getTypeCompositionId().getName());
			composition.setTypeCompositionId(typeComposition);
			Product p1 = new Product(product.getProductPK().getProviderId(),product.getProductPK().getProductId());
			p1.setName(product.getName());
			p1.setPresentation(product.getPresentation());
			p1.setActive(product.getActive());
			p1.setGenericName(product.getGenericName());
			composition.setProduct(p1);
			listComposition.add(composition);
		}
		p.setCompositionCollection(listComposition);
		
		Provider provider = new Provider(product.getProvider().getProviderId(),product.getProvider().getName(),product.getProvider().getClient());
		if(product.getProvider().getAddress() != null)
			provider.setAddress(product.getProvider().getAddress());
		p.setProvider(provider);		
		
		List<Productattributes> listProductAttributesTemp = (List<Productattributes>)product.getProductattributesCollection();
		List<Productattributes> listProductAttributes = new ArrayList<Productattributes>();
		for (Productattributes pas : listProductAttributesTemp) {
			Productattributes productAttributes = new Productattributes(pas.getProductattributesPK().getProductAttributeId(),pas.getProductattributesPK().getProviderId(),pas.getProductattributesPK().getProductId()); 
			Productattribute pa = new Productattribute(pas.getProductattributesPK().getProductAttributeId(),pas.getProductattribute().getName(),pas.getProductattribute().getDetail(),pas.getProductattribute().getOrder());
			productAttributes.setProductattribute(pa);
			listProductAttributes.add(productAttributes);
		}		
		p.setProductattributesCollection(listProductAttributes);		
		return p;
	}
	
	private Product getProductTemp(Product product){
		Product p = new Product(product.getProductPK().getProviderId(),product.getProductPK().getProductId());
		p.setName(product.getName());
		p.setPresentation(product.getPresentation());
		p.setActive(product.getActive());
		p.setGenericName(product.getGenericName());
		Activesubstance as = new Activesubstance(product.getActiveSubstanceId().getActiveSubstanceId(),product.getActiveSubstanceId().getSynonyms(),product.getActiveSubstanceId().getName(),product.getActiveSubstanceId().getTherapeuticAction(),product.getActiveSubstanceId().getProperties());
		p.setActiveSubstanceId(as);
		p.setCode(product.getCode());
		p.setCodeBar(product.getCodeBar());
		
		Provider provider = new Provider(product.getProvider().getProviderId(),product.getProvider().getName(),product.getProvider().getClient());
		if(product.getProvider().getAddress() != null)
			provider.setAddress(product.getProvider().getAddress());
		p.setProvider(provider);					
		
		List<Composition> listCompositionTemp = (List<Composition>)product.getCompositionCollection();
		List<Composition> listComposition = new ArrayList<Composition>();
		for (Composition c : listCompositionTemp) {
			Composition composition = new Composition(c.getCompositionId(),c.getName(),c.getQuantity(),c.getActive());
			Typecomposition typeComposition = new Typecomposition(c.getTypeCompositionId().getTypeCompositionId(),c.getTypeCompositionId().getName());
			composition.setTypeCompositionId(typeComposition);
			Product p1 = new Product(product.getProductPK().getProviderId(),product.getProductPK().getProductId());
			p1.setName(product.getName());
			p1.setPresentation(product.getPresentation());
			p1.setActive(product.getActive());
			p1.setGenericName(product.getGenericName());
			composition.setProduct(p1);
			listComposition.add(composition);
		}
		List<Productattributes> listProductAttributesTemp = (List<Productattributes>)product.getProductattributesCollection();
		List<Productattributes> listProductAttributes = new ArrayList<Productattributes>();
		for (Productattributes pa : listProductAttributesTemp) {
			Productattributes productAttributes = new Productattributes(pa.getProductattributesPK().getProductAttributeId(),pa.getProductattributesPK().getProviderId(),pa.getProductattributesPK().getProductId()); 
			listProductAttributes.add(productAttributes);
		}
		p.setCompositionCollection(listComposition);
		p.setProductattributesCollection(listProductAttributes);
		
		if(product.getPharmacyProduct() != null){
			Pharmacyproduct pp = new Pharmacyproduct(product.getPharmacyProduct().getPharmacyproductPK().getPharmacyId(),product.getPharmacyProduct().getPharmacyproductPK().getProviderId(),product.getPharmacyProduct().getPharmacyproductPK().getProductId()); 
			pp.setRepositionLevel(product.getPharmacyProduct().getRepositionLevel());
			pp.setPackage1(product.getPharmacyProduct().getPackage1());
			pp.setService(product.getPharmacyProduct().getService());
			pp.setRequiresPrescription(product.getPharmacyProduct().getRequiresPrescription());
			pp.setLocation(product.getPharmacyProduct().getLocation());
			pp.setActive(product.getPharmacyProduct().getActive());
			pp.setValueTempCountItem(product.getPharmacyProduct().getValueTempCountItem());
			List<Package> listPackage = new ArrayList<Package>(); 
			
			
			List<Package> listPackageTemp = (List<Package>)product.getPharmacyProduct().getPackageCollection();	
			//System.out.println(listPackageTemp.size()+" ************************ ");
			for (Package package1 : listPackageTemp) {
				List<Item> listItem = new ArrayList<Item>();
				List<Item> listItemTemp = (List<Item>)package1.getItemCollection();
				for (Item item : listItemTemp) {
					Item itemTemp = new Item(item.getItemPK().getPackageId(),item.getItemPK().getItemId());
					Stock s = new Stock(item.getStockId().getStockId(),item.getStockId().getName());
					itemTemp.setTempState(item.getTempState());
					itemTemp.setState(item.getState());
					itemTemp.setCost(item.getCost());
					itemTemp.setStockId(s);
					listItem.add(itemTemp);
				}
				Package pack = new Package(package1.getPackageId(),package1.getPackage1(),package1.getDateIncome(),package1.getDueDate());
				pack.setBatchNumber(package1.getBatchNumber());
				pack.setDueDate(package1.getDueDate());
				pack.setState(package1.getState());
				if(package1.getTempTotal1() != null)
					pack.setTempTotal1(package1.getTempTotal1());
				
				if(package1.getTempTotal2() != null)
					pack.setTempTotal2(package1.getTempTotal2());
				
				pack.setItemCollection(listItem);
				listPackage.add(pack);
			}	
			pp.setPackageCollection(listPackage);
			p.setPharmacyProduct(pp);
		}
		return p;
	}
	private ArrayList<Product> getListProductTempWithItems(List<Product> listProductTemp){
		ArrayList<Product> listProduct = new ArrayList<Product>();
		Product p = null;
		for (Product product : listProductTemp) {	
			p = getProductTemp(product);
			if(p != null)
				listProduct.add(p);
		}
		return listProduct;
	}	
	@RequestMapping(value = "/saleLoadProductSelected", method = RequestMethod.GET)
   	public @ResponseBody Product handleRequestSaleLoadProductSelected(HttpServletRequest request){		
		return getProductTemp(configServiceProducts.searchProductByProviderIdByProductId(UtilConverter.converterStringToInteger(request,"_providerId"),UtilConverter.converterStringToInteger(request,"_productId"), s_pharmacyId, true, UtilConverter.converterStringToInteger(request,"stockId")));
    }
	
	@RequestMapping(value="/saleShowEditPharmacyProduct", method=RequestMethod.GET)
	public String handleRequestSaleShowDetailPharmacyProduct(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){	
			return UtilCommon.fReferenceAdd+"showEditPharmacyProduct";
		}else
			return redirectTransactionSellProducts(request);
	}
	
	@RequestMapping(value="/saleShowDetailProduct", method=RequestMethod.GET)
	public String handleRequestSaleShowDetailProduct(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){	
			return UtilCommon.fReferenceAdd+"showDetailProduct";
		}else
			return redirectTransactionSellProducts(request);
	}
	
	@RequestMapping(value="/saleShowFormItemSimple", method=RequestMethod.GET)
	public String handleRequestSaleShowFormItemSimple(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){	
			return UtilCommon.fReferenceAdd+"showFormItemSimple";
		}else
			return redirectTransactionSellProducts(request);
	}
	
	@RequestMapping(value="/transactionRegisterSell", method=RequestMethod.POST)
	public @ResponseBody String handleRequestTransactionRegisterSell(HttpServletRequest request, Model model)throws Exception {
		short sUserId = UtilConverter.converterStringToShort(request,"userId");
		if(buyProductsTransactionService.addTransaction(request, s_pharmacyId,listProductGlobal,sUserId) && (short)sUserId != -1)
			return "OK";
		else
			throw new IllegalArgumentException("La Transaccion no fue completada debido a un error!!!!!!!!!");	
	}
	@ExceptionHandler(IllegalArgumentException.class)
	@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public ExceptionObject handleException(IllegalArgumentException ex, HttpServletResponse response) throws IOException{
		ExceptionObject exceptionObject = new ExceptionObject("mapping -> transactionRegisterSell", " Class -> TransactionSellProductsController ", ex.getMessage());
		return exceptionObject;
	}	
	@RequestMapping(value = "/saleShowListClientByNitCi", method = RequestMethod.GET)
   	public @ResponseBody String handleRequestSaleShowListClientByNitCi(HttpServletRequest request){	
		List<Client> clients = buyProductsTransactionService.getListClientByPharmacyIdByNitByActive(s_pharmacyId,UtilConverter.converterStringToString(request,"nitCi"),true);
		System.out.println(clients);
		String string = "[";
        int i = 0;
		for(Client cl : clients){
            string += "{\"label\":\""+cl.getName()+" NIT: "+cl.getNit();
            string += "\",\"value\":\""+cl.getNit();
            string += "\",\"name\":\""+cl.getName();
            string += "\",\"nit\":\""+cl.getNit();
            string += "\"},";
            i++;
        }	
		if(i > 0){
            i = string.lastIndexOf(",");
            string = string.substring(0, i);
            string += "]";
        }
		return string;
    }			
	@RequestMapping(value="/saleShowFormBill", method=RequestMethod.GET)
	public String handleRequestSaleShowFormBill(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){	
			double amountTemp = UtilConverter.converterStringToDouble(request,"_amountTotal"); 
			model.addAttribute("dateTemp",UtilCommon.getDateSpanishLatin());
			model.addAttribute("literalAmount",UtilTransaction.getLiteralFormat(amountTemp));
			return UtilCommon.fReferenceAdd+"showFormBill";
		}else
			return redirectTransactionSellProducts(request);
	}
	@RequestMapping(value="/showDetailError", method=RequestMethod.GET)
	public String handleRequestShowDetailError(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request))
			return UtilCommon.fReferenceAdd+"showDetailError";
		else
			return redirectTransactionSellProducts(request);
	}
	@RequestMapping(value="/showFormCredit", method=RequestMethod.GET)
	public String handleRequestShowFormCredit(HttpServletRequest request, Model model) throws ServletException {
		if(this.sessionControl(request)){
			/*
			Enumeration enumeration = request.getParameterNames();
	        while (enumeration.hasMoreElements()) {
	            String parameterName = (String) enumeration.nextElement();
	            System.out.print(parameterName+"   < ***** >");
	            System.out.println(request.getParameter(parameterName));
	        }
	        */
	        
	        
	        
	        
			int valCreditTemp = UtilConverter.converterStringToInteger(request,"cfc");
	        if(valCreditTemp == 2){
	        	//System.out.println(s_UserPharmacy);
	        	Client c = buyProductsTransactionService.searchClient(request,s_UserPharmacy);
	        	if(c != null){
		        	/*
	        		List<Accountreceivable> listAccountReceivable = (List)c.getAccountreceivableCollection();
		        	for (Accountreceivable accountreceivable : listAccountReceivable) {
		        		System.out.println(accountreceivable);
						
		        		List<Paymentplan> lisPaymentPlan = (List)accountreceivable.getPaymentplanCollection();
						for (Paymentplan paymentplan : lisPaymentPlan) {
							System.out.println(paymentplan);
						}
					
					}
					*/
	        		if(c.getAccountreceivableCollection().size() > 0){
	        			List<Accountreceivable> listAccountReceivable = (List)c.getAccountreceivableCollection();
		        		model.addAttribute("listAccountReceivable",listAccountReceivable);
	        		}
	        		model.addAttribute("clientTemp",c);
	        	}
	        }	        
			return UtilCommon.fReferenceAdd+"showFormCredit";
		}else
			return redirectTransactionSellProducts(request);
	}
	

	
	
	/*		// Integer.parseInt("sdfasdfdf");
		Enumeration enumeration = request.getParameterNames();
        while (enumeration.hasMoreElements()) {
            String parameterName = (String) enumeration.nextElement();
            System.out.print(parameterName+"   < ***** >");
            System.out.println(request.getParameter(parameterName));
        }
       */
}
